#include <REGX52.H>
#include "uart.c"

#define RECORDS_MAX 8

#define KEYS P1
#define LEDS P2
sbit KEY_RECORD = P3 ^ 6;
sbit KEY_PLAY = P3 ^ 7;
#define PRESSED_RECORD 99
#define PRESSED_PLAY 101

#define STATE_RECORD 1
#define STATE_PLAY 2

unsigned char state = STATE_RECORD;

unsigned char key_records[RECORDS_MAX];
// 数组可以记录不满，使用index保存记录总量的最后一位的位置
unsigned char records_index = 0;

void delay_ms(unsigned int ms)
{
    unsigned int i, j;
    for (i = 0; i < ms; i++)
    {
        for (j = 0; j < 123; j++)
            ;
    }
}

unsigned char key_scan()
{
    unsigned char rlt = 0xFF;
    // 0~7任意一个按键被按下
    if (KEYS != 0xFF)
    {
        rlt = KEYS;
        // switch (KEYS)
        // {
        // case 0xFE:
        //     rlt = 0x01;
        //     break;
        // case 0xFD:
        //     rlt = 0x02;
        //     break;
        // case 0xFB:
        //     rlt = 0x04;
        //     break;
        // case 0xF7:
        //     rlt = 0x08;
        //     break;
        // case 0xEF:
        //     rlt = 0x10;
        //     break;
        // case 0xDF:
        //     rlt = 0x20;
        //     break;
        // case 0xBF:
        //     rlt = 0x40;
        //     break;
        // case 0x7F:
        //     rlt = 0x80;
        //     break;
        // default:
        //     break;
        // }
        while (KEYS != 0xFF)
        {
        }
    }

    return rlt;
}

void play()
{
    unsigned char i;
    LEDS = 0xFF;
    while (1)
    {
        for (i = 0; i < records_index; i++)
        {
            LEDS = key_records[i];
            delay_ms(500);
            if (KEY_RECORD == 0)
            {
                while (KEY_RECORD == 0)
                {
                }
                state = STATE_RECORD;
                return;
            }
        }

        if (KEY_RECORD == 0)
        {
            while (KEY_RECORD == 0)
            {
            }
            state = STATE_RECORD;
            return;
        }
    }
}

void record_keys()
{
    unsigned char key;
    LEDS = 0xFF;
    records_index = 0;
    // 播放按键被按下，结束

    while (1)
    {
        key = key_scan();
        if (key != 0xFF)
        {
            key_records[records_index] = key;
            records_index++;
            LEDS &= key;
            printf("%x\n", (int)(~key));
        }

        if (KEY_PLAY == 0)
        {
            while (KEY_PLAY == 0)
            {
            }
            state = STATE_PLAY;
            return;
        }
    }
}

void main()
{
    // unsigned char key;
    uart_init();
    while (1)
    {
        // key = key_scan();
        // if (key != 0xFF)
        // {
        //     printf("%x\n", (int)key);
        // }

        switch (state)
        {
        case STATE_PLAY:
            play();
            break;
        case STATE_RECORD:
            record_keys();
            break;
        default:
            break;
        }
    }
}